package com.jy.adscm.operation.mscyb.service.impl;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cg.bean.CgMaterial;
import com.jy.adscm.operation.cg.mapper.mysql.CgMaterialMapper;
import com.jy.adscm.operation.mscyb.bean.*;
import com.jy.adscm.operation.mscyb.mapper.mysql.*;
import com.jy.adscm.operation.mscyb.service.JqdbMaterialListService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.operation.mscyb.service.JqylMaterialService;
import com.jy.adscm.operation.purchase.bean.Purchasebom;
import com.jy.adscm.operation.purchase.mapper.mysql.PurchasebomMapper;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zyl
 * @since 2019-06-18
 */
@Service
public class JqdbMaterialListServiceImpl extends ServiceImpl<JqdbMaterialListMapper, JqdbMaterialList> implements JqdbMaterialListService {

    @Autowired
    JqylMaterialService jqylMaterialService;
    @Autowired
    CgMaterialMapper cgMaterialMapper;
    @Autowired
    JqdbMaterialMapper jqdbMaterialMapper;
    @Autowired
    JqylMaterialdetailMapper jqylMaterialdetailMapper;
    @Autowired
    JqdbMachinepackingMapper jqdbMachinepackingMapper;
    @Autowired
    JqylSettingMaterialCheckMapper jqylSettingMaterialCheckMapper;
    @Autowired
    JqdbMaterialListCheckMapper jqdbMaterialListCheckMapper;
    @Autowired
    JqylMaterialMapper jqylMaterialMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertJqdbMaterialList(JqdbMaterialList jqdbMaterialList, Token token) throws AdscmSystemException{

        float temp=  jqdbMaterialList.getNum();

        int num= (int)temp ;
          boolean isInt=true;
        if (temp==num){

        }else {
            num=1;
            isInt=false;
        }

        for (int i = 0; i < num; i++) {
            if (isInt){
                jqdbMaterialList.setNum(1f);
            }else {
                jqdbMaterialList.setNum(temp);
            }

            //根据这个查询原来库存中是否还存在余料
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqdbMaterialList.getName(), null)) {

                //修改库存  减去库存  num相反数

                JqylMaterial jqylMaterial = jqylMaterialService.updateJqylMaterialyValue(jqdbMaterialList.getName(), jqdbMaterialList.getNum()*-1);

                //根据任务书中的物料名称获取到物料的编码
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
                if (!AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    throw new AdscmSystemException("找不到该物料编码");
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getType(),null)){
                    jqdbMaterialList.setType(cgMaterial.getType());
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getBatchnums(),null)){
                    jqdbMaterialList.setBatch(jqylMaterial.getBatchnums());
                }
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial.getCode(),null)){
                    //查询今天最大的号
                    if (jqdbMaterialList.getNum()==1){
                        String yearMonth = new SimpleDateFormat("yyMMdd").format(new Date());
                        String code=cgMaterial.getCode().trim()+yearMonth;
                        Wrapper<JqdbMaterialList> wrapper =new EntityWrapper<>();
                        wrapper.like("code",code, SqlLike.RIGHT);
                        wrapper.orderBy("code",false);
                        List<JqdbMaterialList> jqdbMaterialLists = super.selectList(wrapper);
                        if (jqdbMaterialLists!=null && jqdbMaterialLists.size()>0){
                            JqdbMaterialList jqdbMaterialList1 = jqdbMaterialLists.get(0);
                            code=jqdbMaterialList1.getCode().replace(cgMaterial.getCode().trim(),"");
                            Long tempcode= Long.valueOf(code)+1;
                            jqdbMaterialList.setCode(cgMaterial.getCode().trim()+String.valueOf(tempcode));
                        }else {
                            jqdbMaterialList.setCode(cgMaterial.getCode().trim()+yearMonth+"001");
                        }
                    }

                }
                //添加用料信息
                jqdbMaterialList.setCreateTime(new Date());
                jqdbMaterialList.setCreator(token.getUser().getId().toString());
                jqdbMaterialList.setState(null);
                //默认使用时间为当前
                jqdbMaterialList.setUseTime(new Date());
                super.insert(jqdbMaterialList);

                //如果提交的数量和计划的数量相等，默认完成装配
                JqdbMaterial jqdbMaterial = jqdbMaterialMapper.selectById(jqdbMaterialList.getPid());
                Wrapper<JqdbMaterialList> getAllWrapper=new EntityWrapper<>();
                getAllWrapper.eq("pid",jqdbMaterial.getId());
                getAllWrapper.eq("state","1");
                List<JqdbMaterialList> jqdbMaterialLists = super.selectList(getAllWrapper);
                float tempNum=jqdbMaterialList.getNum();//默认算上当前这条
                for (JqdbMaterialList materialList : jqdbMaterialLists) {
                    tempNum=tempNum+materialList.getNum();
                }
                if (jqdbMaterial.getNum()<tempNum){
                    throw  new AdscmSystemException("添加数量大于了需求数量");

                }
                if (jqdbMaterial.getNum()==tempNum){
                    jqdbMaterial.setIsAssembly(1);
                    jqdbMaterialMapper.updateById(jqdbMaterial);
                }else {
                    jqdbMaterial.setIsAssembly(0);
                    jqdbMaterialMapper.updateById(jqdbMaterial);
                }
                //出库信息
                JqylMaterialdetail jqylMaterialdetail=new JqylMaterialdetail();
                jqylMaterialdetail.setName(jqylMaterial.getResourcename());
                jqylMaterialdetail.setTypenums(jqylMaterial.getTypenums());
                jqylMaterialdetail.setUnit(jqylMaterial.getUnit());
                jqylMaterialdetail.setBatchnums(jqylMaterial.getBatchnums());
                //设置这个部件的编码
                JqdbMachinepacking jqdbMachinepacking = jqdbMachinepackingMapper.selectById(jqdbMaterial.getTid());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jqdbMachinepacking,null)){
                    jqylMaterialdetail.setPcode(jqdbMachinepacking.getTaskcode());
                }
                jqylMaterialdetail.setOutstorageaddtime(new Date());
                if (AdscmBaseUtils.getInstance().isNotEmpty(token,null)){
                    jqylMaterialdetail.setUseperson(token.getUser().getId().toString());
                }else {
                    throw  new AdscmSystemException("请重新登录");
                }
                jqylMaterialdetail.setIsrepair(0);
                jqylMaterialdetail.setUsenums( Double.valueOf(jqdbMaterialList.getNum()) );
                jqylMaterialdetail.setMaterialstate(jqdbMaterialList.getState());
                jqylMaterialdetail.setPid(jqdbMaterialList.getId().toString());
                jqylMaterialdetail.setOutstoragetime(jqdbMaterialList.getUseTime());
                jqylMaterialdetail.setTid(jqylMaterial.getTid().toString());
                jqylMaterialdetail.setCode(jqdbMaterialList.getCode());
                jqylMaterialdetail.setMaterialstate("1");
                jqylMaterialdetailMapper.insert(jqylMaterialdetail);
                //生成检验记录
                Wrapper<JqylSettingMaterialCheck> wrapper =new EntityWrapper<>();
                wrapper.eq("pid",cgMaterial.getId());
                wrapper.eq("isEnable",1);

                List<JqylSettingMaterialCheck> jqylSettingMaterialChecks = jqylSettingMaterialCheckMapper.selectList(wrapper);

                if (jqylSettingMaterialChecks!=null && jqylSettingMaterialChecks.size()>0 ){
                    for (JqylSettingMaterialCheck jqylSettingMaterialCheck : jqylSettingMaterialChecks) {
                        JqdbMaterialListCheck  jqdbMaterialListCheck =new JqdbMaterialListCheck();
                        jqdbMaterialListCheck.setPid(jqdbMaterialList.getId());
                        jqdbMaterialListCheck.setCid(jqylSettingMaterialCheck.getId());
                        jqdbMaterialListCheck.setName(jqylSettingMaterialCheck.getName());
                        jqdbMaterialListCheck.setReference(jqylSettingMaterialCheck.getReference());
                        jqdbMaterialListCheck.setType(jqylSettingMaterialCheck.getType());
                        jqdbMaterialListCheck.setUnit(jqylSettingMaterialCheck.getUnit());
                        jqdbMaterialListCheck.setRemark(jqylSettingMaterialCheck.getRemark());
                        jqdbMaterialListCheck.setRank(jqylSettingMaterialCheck.getRank());
                        jqdbMaterialListCheckMapper.insert(jqdbMaterialListCheck);
                    }
                    jqdbMaterialList.setIsCheck(1);
                }else {
                    jqdbMaterialList.setIsCheck(0);
                    jqdbMaterialList.setState("1");

                }
                super.updateById(jqdbMaterialList);
            }
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteJqdbMaterialList(Integer id) throws AdscmSystemException{
        //1.查询出该条记录
        JqdbMaterialList jqdbMaterialList = super.selectById(id);
        //2.修改回原来的库存
        jqylMaterialService.updateJqylMaterialyValue(jqdbMaterialList.getName(), jqdbMaterialList.getNum());
        ///3.删除掉对应的库存出库记录
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("PID",id);
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        if (jqylMaterialdetails!=null&& jqylMaterialdetails.size()>0){
            JqylMaterialdetail jqylMaterialdetail = jqylMaterialdetails.get(0);
            jqylMaterialdetailMapper.deleteById(jqylMaterialdetail.getId());
        }
        //删除对应的检验记录
        Wrapper<JqdbMaterialListCheck> jqdbMaterialListCheckwrapper=new EntityWrapper<>();
        jqdbMaterialListCheckwrapper.eq("pid",id);
        List<JqdbMaterialListCheck> jqdbMaterialListChecks = jqdbMaterialListCheckMapper.selectList(jqdbMaterialListCheckwrapper);
        if (jqdbMaterialListChecks!=null && jqdbMaterialListChecks.size()>0){
            for (JqdbMaterialListCheck jqdbMaterialListCheck : jqdbMaterialListChecks) {
                jqdbMaterialListCheckMapper.deleteById(jqdbMaterialListCheck);
            }
        }
        //查询现在这个父级记录，设置他装配状态为未装配
        JqdbMaterial jqdbMaterial = jqdbMaterialMapper.selectById(jqdbMaterialList.getPid());
        jqdbMaterial.setIsAssembly(0);
        jqdbMaterialMapper.updateById(jqdbMaterial);
        boolean b = super.deleteById(id);
        return b;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateJqdbMaterialList(JqdbMaterialList jqdbMaterialList) throws AdscmSystemException {
        if (AdscmBaseUtils.getInstance().isNotEmpty(jqdbMaterialList.getCode(),null)){
            if (jqdbMaterialList.getNum()>1){
                throw  new AdscmSystemException("无法修改数量");
            }
        }
        Wrapper<JqylMaterialdetail> wrapper =new EntityWrapper<>();
        wrapper.eq("pid",jqdbMaterialList.getId());
        List<JqylMaterialdetail> jqylMaterialdetails = jqylMaterialdetailMapper.selectList(wrapper);
        JqylMaterialdetail jqylMaterialdetail =null;
        if (jqylMaterialdetails!=null &&jqylMaterialdetails.size()>0){
            jqylMaterialdetail=jqylMaterialdetails.get(0);
        }
        JqdbMaterialList oldjqdbMaterialList = super.selectById(jqdbMaterialList.getId());
        Float num=  oldjqdbMaterialList.getNum()-jqdbMaterialList.getNum();
        //数量有变化修改原料库  库存
        if (num!=0){
            jqylMaterialService.updateJqylMaterialyValue(jqdbMaterialList.getName(), num);
        }
        //修改原料的出库记录 数量和状态
        jqylMaterialdetail.setMaterialstate(jqdbMaterialList.getState());
        jqylMaterialdetail.setUsenums(Double.valueOf(jqdbMaterialList.getNum().toString()));
        jqylMaterialdetailMapper.updateById(jqylMaterialdetail);

        boolean b = super.updateById(jqdbMaterialList);
        return b;
    }

    @Override
    public List<JqdbMaterialList> selectByTid(String tid) {
        Wrapper<JqdbMaterialList> wrapper =new EntityWrapper<>();
        wrapper.eq("pid",tid);
        List<JqdbMaterialList> jqdbMaterialLists = super.selectList(wrapper);
        for (JqdbMaterialList jqdbMaterialList : jqdbMaterialLists) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqdbMaterialList.getName(),null)){
                JqylMaterial jqylMaterial = jqylMaterialMapper.selectById(Integer.valueOf(jqdbMaterialList.getName()));
                CgMaterial cgMaterial = cgMaterialMapper.selectById(Integer.valueOf(jqylMaterial.getResourcename()));
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgMaterial,null)){
                    jqdbMaterialList.setNameName(cgMaterial.getName());
                }
            }
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqdbMaterialList.getCreator(),null)){
                JyUser jyUser = jyUserMapper.selectById(jqdbMaterialList.getCreator());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser,null)){
                    jqdbMaterialList.setCreatorName(jyUser.getName());
                }
            }

        }
        return jqdbMaterialLists;
    }

    @Override
    public List<JqylMaterial> queryMaterial(String id) throws AdscmSystemException{
        Wrapper<JqylMaterial> wrapper =new EntityWrapper<>();
        wrapper.setSqlSelect("TID","RESOURCENAME","TASKCODE","REMAININGNUMS");
        wrapper.eq("ISTASKBEGIN",1);
        wrapper.eq("ISTASKEND",0);
        wrapper.eq("RESOURCENAME",id);
        List<JqylMaterial> jqylMaterials = jqylMaterialMapper.selectList(wrapper);
        if(!(jqylMaterials!=null&&jqylMaterials.size()>0)){
            throw new AdscmSystemException("原料库中无存货");
        }
        for (JqylMaterial jqylMaterial : jqylMaterials) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(jqylMaterial.getResourcename(),null)){
                CgMaterial cgMaterial = cgMaterialMapper.selectById(jqylMaterial.getResourcename());
                jqylMaterial.setCgMaterial(cgMaterial);
            }
        }

        return jqylMaterials;
    }
}
